import { type NextRequest, userAgent } from 'next/server';
import createMiddleware from 'next-intl/middleware';

const _defaultLocale = 'zh';
const _defaultLocales = 'zh,en';

const mobilePaths = [
  '/message',
  '/follow',
  '/search',
  '/sections',
  '/login',
  '/register',
  '/avatar',
  '/privacy-policy',
  '/terms',
  /^\/posts\/new(\?[^#]*)?(#.*)?$/,
  /^\/posts\/(\d+)\/edit(\?[^#]*)?(#.*)?$/,
  /^\/(sections|posts|users)\/(\d+)(\?[^#]*)?(#.*)?$/,
  /^\/(\d+)(\?[^#]*)?(#.*)?$/,
  '/',
];

function shouldUseH5(url: URL, deviceType: string) {
  if (deviceType !== 'mobile') {
    return false;
  }
  return mobilePaths.some((path) =>
    typeof path === 'string'
      ? url.pathname.startsWith(path)
      : path.test(url.pathname),
  );
}

export default function middleware(request: NextRequest) {
  const url = request.nextUrl;
  if (
    shouldUseH5(
      url,
      userAgent(request).device.type === 'mobile' ? 'mobile' : 'desktop',
    )
  ) {
    url.searchParams.set('v', 'h5');
  }

  const defaultLocale =
    request.headers.get('x-default-locale') ??
    process.env.APP_DEFAULT_LOCALE ??
    _defaultLocale;
  const handleI18nRouting = createMiddleware({
    locales: (process.env.APP_LOCALES ?? _defaultLocales).split(','),
    defaultLocale,
  });
  const response = handleI18nRouting(request);
  response.headers.set('x-default-locale', defaultLocale);
  return response;
}

export const config = {
  matcher: [
    '/((?!api|lib|images|icons|static|icon|apple-icon|_next|.*\\..*).*)',
  ],
};
